package com.cz.basetool.ui_work.manager;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import android.content.Context;
import android.content.pm.PackageManager;

import com.cz.basetool.ui_work.thread.ThreadManager;
import com.cz.basetool.ui_work.util.log.CZLocalLogPrinter;

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "CrashHandler";
    private static final boolean DEBUG = true;
    //文件路径
    private static Thread.UncaughtExceptionHandler mDefaultCrashHandler;
    private static CrashHandler mCrashHandler = new CrashHandler();
    private Context mContext;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        return mCrashHandler;
    }

    public void init(Context context) {
        mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        mContext = context.getApplicationContext();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            //将文件写入sd卡
            writeToSDcard(ex);
            //写入后在这里可以进行上传操作
            ThreadManager.getInstance().destroy();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        ex.printStackTrace();
        //如果系统提供了默认异常处理就交给系统进行处理，否则自己进行处理。
        if (mDefaultCrashHandler != null) {
            mDefaultCrashHandler.uncaughtException(thread, ex);
        }
    }

    //将异常写入文件
    private void writeToSDcard(Throwable ex) throws IOException, PackageManager.NameNotFoundException {
        CZLocalLogPrinter.getInstance().writeLog("系统错误");
        Writer result = null;
        PrintWriter printWriter = null;

        try {
            result = new StringWriter();
            printWriter = new PrintWriter(result);
            ex.printStackTrace(printWriter);
            CZLocalLogPrinter.getInstance().writeLog("error", result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(result != null){
                result.close();
            }
            if(printWriter != null){
                printWriter.close();
            }
        }

    }
}